//
//  DragViewByPan.m
//  pictureTouchAction
//
//  Created by 李勇 on 2018/8/19.
//  Copyright © 2018年 李勇. All rights reserved.
//

#import "DragViewByPan.h"

@implementation DragViewByPan
{
    CGPoint previousLocation;
}

- (instancetype)initWithImage:(UIImage *)anImage
{
    self = [super initWithImage:anImage];
    if (self)
    {
        self.userInteractionEnabled = YES;
        //直接赋予中心点新值完成图片的移动
//        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        //直接通过仿射变换完成图片的移动
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanByTransform:)];

        self.gestureRecognizers = @[panRecognizer];
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Promote the touched view
    [self.superview bringSubviewToFront:self];
    
    // Remember original location
    previousLocation = self.center;
}

- (void)handlePan: (UIPanGestureRecognizer *) gestureRecognizer
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    CGPoint translation = [gestureRecognizer translationInView:self.superview];
    NSLog(@"translation.x %f translation.y %f", translation.x,translation.y);
    self.center = CGPointMake(previousLocation.x + translation.x,
                              previousLocation.y + translation.y);
}

- (void)handlePanByTransform:(UIPanGestureRecognizer *)gestureRecognizer
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
    {
        CGPoint newCenter = CGPointMake(self.center.x + self.transform.tx, self.center.y + self.transform.ty);
        self.center = newCenter;
        
        CGAffineTransform theTransform = self.transform;
        theTransform.tx = 0.0f;
        theTransform.ty = 0.0f;
        self.transform = theTransform;
        
        return;
    }
    
    CGPoint translation = [gestureRecognizer translationInView:self.superview];
    CGAffineTransform theTransform = self.transform;
    theTransform.tx = translation.x;
    theTransform.ty = translation.y;
    self.transform = theTransform;
}


@end
